package com.haoxin.ai_course.modules.course.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authc.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.haoxin.ai_course.common.base.AbstractController;
import com.haoxin.ai_course.common.utils.HttpJsonResult;
import com.haoxin.ai_course.modules.course.biz.SysUserBusiness;
import com.haoxin.ai_course.modules.course.entity.PO.DecipherPO;
import com.haoxin.ai_course.modules.course.entity.PO.PayPO;
import com.haoxin.ai_course.modules.course.entity.PO.SysUserPO;
import com.haoxin.ai_course.modules.course.entity.VO.PayStatusVO;
import com.haoxin.ai_course.modules.course.entity.VO.SysUserVO;
import com.haoxin.ai_course.modules.sys.entity.SysUser;

import io.lettuce.core.dynamic.annotation.Param;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;

@Slf4j
@RestController
@AllArgsConstructor
@Api(value = "api", tags = "app小程序-用户管理")
@RequestMapping("/app")
//@Api (value="api", hidden=true)
public class WechatLoginController extends AbstractController {
	@Autowired
	SysUserBusiness sysUserBusiness;
//	@Value("${wx.miniapp.configs[0].appid}")
//    String appid;
	@Autowired
	private MapperFacade mapperFacade;
	@GetMapping("wechatLogin")
	@ApiOperation("登录")
	public HttpJsonResult<SysUserVO> login(@ApiParam("授权码") String code) {
		HttpJsonResult<SysUserVO> result = new HttpJsonResult<SysUserVO>();
		try {
			result = sysUserBusiness.login(code);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@PostMapping("updateUser")
	@ApiOperation("修改用户信息")
	public HttpJsonResult<Boolean> updateUser(@ApiParam("用户对象") @RequestBody SysUserPO user) {
		HttpJsonResult<Boolean> result = new HttpJsonResult<Boolean>();
		try {
			Long userId = getUserId();
			result = sysUserBusiness.update(user, userId);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	@ApiOperation("解密并且获取用户手机号码")
	@PostMapping(value = "getUserMobile")
	public HttpJsonResult<SysUserVO> deciphering(@RequestBody DecipherPO decipherPO) {
		HttpJsonResult<SysUserVO> result = new HttpJsonResult<SysUserVO>();
		try {
			result = sysUserBusiness.deciphering(getUser(), decipherPO);
		} catch (AuthenticationException e) {
			// TODO Auto-generated catch block
			result.setMsg("手机号解密失败");
		}
		return result;
	}

	@PostMapping("createUser")
	@ApiOperation("创建用户，提供给互医平台调用")
	public HttpJsonResult<Boolean> createUser(@ApiParam("用户对象") @RequestBody Map<String, String> params,
			HttpServletRequest req) {
		HttpJsonResult<Boolean> result = new HttpJsonResult<Boolean>();
		try {
			result = sysUserBusiness.createUser(params, req.getHeader("sign"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	@GetMapping("checkPayStatus")
	@ApiOperation("检查用户是否已支付")
	public HttpJsonResult<JSONObject> checkPayStatus(@ApiParam("手机号") @Param("tel") String tel,
			@ApiParam("时间戳") @Param("timeStamp") String timeStamp,@ApiParam("签名") @Param("sign") String sign, HttpServletRequest req) {
		log.info("检查支付状态，tel:{},",tel);
		HttpJsonResult<JSONObject> result = new HttpJsonResult<JSONObject>();
		try {
			boolean needSign = req.getHeader("token") == null;
			result = sysUserBusiness.checkPayStatus(tel, timeStamp,sign, needSign);
		} catch (Exception e) {
			e.printStackTrace();
			
		}
		return result;
	}
	@GetMapping("checkPaymentWithSign")
	@ApiOperation("检查用户支付状态")
	public HttpJsonResult<PayStatusVO> checkPaymentWithSign(@ApiParam("手机号") @Param("tel") String tel,
			@ApiParam("时间戳") @Param("timeStamp") String timeStamp,@ApiParam("签名") @Param("sign") String sign, HttpServletRequest req) {
		HttpJsonResult<PayStatusVO> result = new HttpJsonResult<PayStatusVO>();
		try {
			result = sysUserBusiness.checkPaymentWithSign(tel,sign, timeStamp);
		} catch (Exception e) {
			e.printStackTrace();
			result.setMsg("检查支付状态失败，接口发生异常");
			result.setCode(1);
		}
		log.info("支付状态检查，入参：tel:{},pSign{},timeStampStr:{},返回结果：{}",tel,sign,timeStamp,result);
		return result;
	}
	@PostMapping("checkPaymentWithSign")
	@ApiOperation("post方式检查用户支付状态")
	public HttpJsonResult<PayStatusVO> checkPaymentWithSign(@RequestBody PayPO payPo,HttpServletRequest req) {
		HttpJsonResult<PayStatusVO> result = new HttpJsonResult<PayStatusVO>();
		String sign = req.getHeader("sign");
		try {
			result = sysUserBusiness.checkPaymentWithSign(payPo.getTel(),sign, payPo.getTimeStamp());
		} catch (Exception e) {
			e.printStackTrace();
			result.setMsg("检查支付状态失败，接口发生异常");
			result.setCode(1);
		}
		log.info("支付状态检查，入参：tel:{},pSign{},timeStampStr:{},返回结果：{}",payPo.getTel(),sign,payPo.getTimeStamp(),result);
		return result;
	}
	@ApiOperation("使用code换取用户手机号码")
	@GetMapping("/getPhone")
	public HttpJsonResult<SysUserVO> getPhone(@RequestParam(value = "code", required = false) String code) {
		// 获取token
		HttpJsonResult<SysUserVO> result = new HttpJsonResult<SysUserVO>();
		try {
			
			SysUser user = getUser();
			log.info("获取手机号，用户信息：{}",user);
			if(user.getMobile() != null) {
				SysUserVO sysUserVO = mapperFacade.map(user, SysUserVO.class) ;
				result.setData(sysUserVO);
				log.info("获取手机号，手机号不为空，直接返回用户信息");
				return result;
			}
			log.info("获取手机号，手机号为空调用获取手机号的方法。");
			result = sysUserBusiness.getPhone(code,user);
		} catch (AuthenticationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.error("获取手机号失败，错误信息：" + e.getMessage());
		}
		return result;
	}
}
